package com.budwk.app.sqfwV2.service.publicSecurity.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.enums.SqfwFormSummaryFieldEnum;
import com.budwk.app.sqfw.enums.StreetEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.dto.CompleteFlowTemplateCodeUpdateDTO;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.component.SummarySafetyCommponent;
import com.budwk.app.sqfwV2.dto.PlaceParamDTO;
import com.budwk.app.sqfwV2.dto.dto.SqfwShopBaseInfoDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.dto.publicSecurity.PublicSecurityDTO;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.enums.publicSecurity.PublicSecurityFileEnum;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sqfwV2.service.SummarySafetyService;
import com.budwk.app.sqfwV2.service.publicSecurity.PublicSecurityExcelService;
import com.budwk.app.sqfwV2.service.publicSecurity.PublicSecurityPdfService;
import com.budwk.app.sqfwV2.service.publicSecurity.PublicSecurityService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.util.cri.SimpleCriteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.springframework.util.ObjectUtils;

import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.createExcelAndUpload;

/**
 * @author zhangp
 * @description TODO
 * @className PublicSecurityServiceImpl
 * @Date 11:58 2024/3/27
 */
@Slf4j
@IocBean
public class PublicSecurityServiceImpl implements PublicSecurityService {
    @Inject
    private PublicSecurityPdfService publicSecurityPdfService;
    @Inject
    private PublicSecurityExcelService publicSecurityExcelService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private SqfwFormSummaryService sqfwFormsummaryService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SummarySafetyService summarySafetyService;

    @Inject
    private SummarySafetyCommponent summarySafetyCommponent;


    @Override
    public Sqfw_formSummary_new submitData(CompleteFlowTemplateCodeUpdateDTO dto) {

        CompleteFlowPdfParamForController param = new CompleteFlowPdfParamForController();

        TemplateCodeUpdateDTO templateCodeUpdateDTO = new TemplateCodeUpdateDTO();
        templateCodeUpdateDTO.setCompleteFlow(dto.getCompleteFlow());
        templateCodeUpdateDTO.setFormSummary(dto.getFormSummary());
        summarySafetyCommponent.createOneTask(templateCodeUpdateDTO, null, SupportBusinessTypeEnum.PUBLIC_SECURITY.getName());

        // 组装参数
        CompleteFlowTemplateCodeUpdateDTO codeUpdateDTO = new CompleteFlowTemplateCodeUpdateDTO();
        codeUpdateDTO.setCompleteFlow(templateCodeUpdateDTO.getCompleteFlow());
        codeUpdateDTO.setFormSummary(templateCodeUpdateDTO.getFormSummary());
        param.setCompleteFlowDataDTO(codeUpdateDTO);
        param.setUserId(SecurityUtil.getUserId());
        publicSecurityPdfService.createPdfAndMsg(param);
        return dto.getFormSummary();
    }

    @Override
    public Result<?> reGeneratePDF(String sqfwFlowId) {
        CompleteFlowPdfParamForController param = new CompleteFlowPdfParamForController();
        param.setCompleteFlowId(sqfwFlowId);
        publicSecurityPdfService.reCreatePdfAndMsg(param);
        return Result.success();
    }

    @Override
    public Result<?> downExcelLedger(DownExcelLedgerReqVo reqVo) {
        List<ExcelCreateConfig> excelConfigList = CommonComponent.getExcelConfigList(reqVo);
        List<GenerateExcelUrlVO> generateExcelUrlVOS = publicSecurityExcelService.generateExcel(excelConfigList, SecurityUtil.getUserId(), reqVo.getSqfwIds());
        return Result.data(generateExcelUrlVOS);
    }

    @Override
    public List<String> isCheckDataBatch(List<String> sqfwIdList) {
        List<String> indexList = new ArrayList<>();
        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "in", sqfwIdList);
        cnd.and("type", "=", SqfwFormSummaryConstants.public_security);
        cnd.orderBy("fill_date", "desc");
        List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.query(cnd);
        if (formSummaryList.isEmpty()) return indexList;
        for (PublicSecurityFileEnum item : PublicSecurityFileEnum.values()) {
            indexList.add(item.getCode());
        }
        return indexList;
    }

    @Override
    public Result<?> downloadTemplate(String index, String tag) {
        Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());
        /*PublicSecurityFileEnum publicSecurityFileEnum = PublicSecurityFileEnum.getPublicSecurityFileByCode(index);
        if (ObjectUtils.isEmpty(publicSecurityFileEnum)) {
            throw new ServiceException("模板不存在");
        }
        GenerateExcelUrlVO resultVO = new GenerateExcelUrlVO();
        String fileName = publicSecurityFileEnum.getName() + "." + publicSecurityFileEnum.getSuffix();
        String emptyTemplate = publicSecurityFileEnum.getEmptyTemplatePath();
        String filepath = CommonFormOfficeUtils.getTemplatePathByOS(emptyTemplate);
        if (publicSecurityFileEnum.getSuffix().contains("doc")) {
            ByteArrayOutputStream byteArrayOutputStream = CommonFormOfficeUtils.generateWordDocument(new HashMap<>(), emptyTemplate, null, System.currentTimeMillis());
            GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = CommonFormOfficeUtils.wordUpload(byteArrayOutputStream, publicSecurityFileEnum.getName(), null);
            resultVO.setCreateConditionFlag(true);
            resultVO.setExcelUrl(generateWordAndPdfUrlVO.getWordUrl());
        } else {
            ExcelFileCreateParamBO excelFileCreateParam = new ExcelFileCreateParamBO();
            excelFileCreateParam.setTemplatePath(filepath);
            excelFileCreateParam.setSheetParam(null);
            excelFileCreateParam.setDataList(Lists.newArrayList());
            excelFileCreateParam.setFileName(fileName);
            excelFileCreateParam.setListNotLastRow(null);
            resultVO.setCreateConditionFlag(true);
            resultVO.setExcelUrl(createExcelAndUpload(excelFileCreateParam));
        }*/
        GenerateExcelUrlVO resultVO = downloadTemplateByIndex(index);
        return Result.data(resultVO);
        // 下载文件
        //CommonComponent.downFile(response, filepath, fileName);
    }

    @Override
    public Result<?> getShopInfoListByContent(String content, Integer pageSize, Integer pageNo, List<String> types) {
       /* if (ObjectUtils.isEmpty(types)) {
            List<String> typeList = new ArrayList<>();
            typeList.add(SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode());
            types = typeList;
        }*/
        String type = SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode();
        return Result.data(shopsBaseInfoService.getShopInfoByPlaceName(content, pageSize, pageNo, type));
    }

    @Override
    public Result<?> getFormSummaryInfoListByShopId(String shopBaseInfoId) {
        SimpleCriteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        criSql.andEquals(Sqfw_formSummary_new::getShopsBaseInfoId, shopBaseInfoId)
                .andEquals(Sqfw_formSummary_new::getType, SupportBusinessTypeEnum.PUBLIC_SECURITY.getName());
        cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        Sqfw_formSummary_new formSummaryNew = sqfwFormsummaryNewService.fetch(cri);
        //当记录没有时组装数据
        if (ObjectUtil.isEmpty(formSummaryNew)) {
            PublicSecurityDTO publicSecurityDTO = new PublicSecurityDTO();
            Sqfw_formSummary_new formSummaryNewBuild = new Sqfw_formSummary_new();
            SqfwShopsBaseInfo info = shopsBaseInfoService.fetch(shopBaseInfoId);
            if (ObjectUtils.isEmpty(info)) {
                throw new ServiceException("场所信息不存在！");
            }
            //publicSecurityDTO.setPlaceType(info.getMainBusinessScope());
            publicSecurityDTO.setPlaceName(info.getPlaceName());
            publicSecurityDTO.setAddress(info.getAddress());
            publicSecurityDTO.setOperatorTelephone(info.getOperatorTelephone());
            publicSecurityDTO.setOperator(info.getOperator());
            publicSecurityDTO.setRiskDescription(null);
            publicSecurityDTO.setWhetherThereIsAnyHiddenDanger(false);
            publicSecurityDTO.setInCrimeAndEvilClues(null);
            publicSecurityDTO.setInCrimeAndEvil(false);
            formSummaryNewBuild.setParamData(JSON.toJSONString(publicSecurityDTO));
            formSummaryNewBuild.setShopsBaseInfoId(info.getId());
            formSummaryNewBuild.setShopsBaseInfo(info);
            return Result.data(formSummaryNewBuild);

        }
        return Result.data(formSummaryNew);
    }

    @Override
    public List<SqfwShopBaseInfoDTO> getPlaceInfoList(String status, Integer pageNo, Integer pageSize, String content) {
        Sys_user sysUser = sysUserService.getUserById(SecurityUtil.getUserId());
        StringBuilder sqlStr = new StringBuilder();
       /* sqlStr.append(" select * from (");
        sqlStr.append(" select *,case  when TO_CHAR(now() , 'IW')!=TO_CHAR(fill_date , 'IW') then 1 else 0 end as timeout_status from (");
        sqlStr.append(" select ");
        sqlStr.append(" id,");
        sqlStr.append(" place_name,");
        sqlStr.append(" operator,");
        sqlStr.append(" address,");
        sqlStr.append(" operator_telephone, ");
        sqlStr.append(" case when fill_date is null then create_date else fill_date end fill_date,");
        sqlStr.append(" CASE WHEN deleted = true THEN 3 ELSE 1 END as check_status  ");
        sqlStr.append(" from shequ.sqfw_shops_base_info ssbi where 1=1");
        sqlStr.append(" and province ='").append(sysUser.getProvince()).append("'");
        sqlStr.append(" and city ='").append(sysUser.getCity()).append("'");
        sqlStr.append(" and district ='").append(sysUser.getDistrict()).append("'");
        if (!CommonConstants.DIRECTLY_UNDER.equals(sysUser.getCounty())) {
            sqlStr.append(" and county ='").append(sysUser.getCounty()).append("'");
        }
        //sqlStr.append(" and county ='").append(sysUser.getCounty()).append("'");
        if (!CommonConstants.DIRECTLY_UNDER.equals(sysUser.getCommunity())) {
            sqlStr.append(" and community ='").append(sysUser.getCommunity()).append("'");
        }
        sqlStr.append(" and service_type ='%").append(SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode()).append("%'");
        //sqlStr.append(" and type ='").append(ServiceTypeEnum.PUBLIC_SECURITY.getName()).append("'");
        sqlStr.append(" )b ) a where 1=1  ");
        //超时状态status，0-全部,1-已超时，2-未超时
        if (SqfwFormSummaryFieldEnum.check_status_checked.getCode().equals(status)) {
            sqlStr.append(" and a.timeout_status ='0' and  a.check_status <> 3");
        }
        if (SqfwFormSummaryFieldEnum.check_status_init.getCode().equals(status)) {
            sqlStr.append(" and a.timeout_status ='1' and  a.check_status <> 3");
        }
        if (SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode().equals(status)) {
            sqlStr.append(" and a.check_status = 3");
        }
        if (StringUtils.isNotBlank(content)) {
            sqlStr.append(" and (a.place_name like '%").append(content).append("%' or a.address like '%").append(content).append("%') ");
        }*/
        sqlStr.append(" select * from (");
        sqlStr.append(" select d.*,case  when TO_CHAR(now() , 'IW')!=TO_CHAR(d.fill_date , 'IW') then 1 else 0 end as timeout_status from (");
        sqlStr.append(" select a.*,case when c.fill_date is null then a.create_date else c.fill_date end fill_date from (");
        sqlStr.append(" select ");
        sqlStr.append(" id,");
        sqlStr.append(" place_name,");
        sqlStr.append(" operator,");
        sqlStr.append(" address,");
        sqlStr.append(" operator_telephone, ");
        sqlStr.append(" create_date,");
        sqlStr.append(" CASE WHEN shop_status='3' THEN 3 ELSE 1 END as check_status  ");
        sqlStr.append(" from shequ.sqfw_shops_base_info ssbi where 1=1");
        sqlStr.append(" and province ='").append(sysUser.getProvince()).append("'");
        sqlStr.append(" and city ='").append(sysUser.getCity()).append("'");
        sqlStr.append(" and district ='").append(sysUser.getDistrict()).append("'");
        if (!CommonConstants.DIRECTLY_UNDER.equals(sysUser.getCounty())) {
            sqlStr.append(" and county ='").append(sysUser.getCounty()).append("'");
        }
        //sqlStr.append(" and county ='").append(sysUser.getCounty()).append("'");
        if (!CommonConstants.DIRECTLY_UNDER.equals(sysUser.getCommunity())) {
            sqlStr.append(" and community ='").append(sysUser.getCommunity()).append("'");
        }
        sqlStr.append(" and service_type like '%").append(SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode()).append("%'");
        //sqlStr.append(" and type ='").append(ServiceTypeEnum.PUBLIC_SECURITY.getName()).append("'");
        sqlStr.append(" ) a   ");
        sqlStr.append(" left join ( ").append(buildFormSummarySql(sysUser)).append(" )c on c.shops_base_info_id=a.id   ");
        sqlStr.append(" ) d ) e where 1=1   ");
        //超时状态status，0-全部,1-已超时，2-未超时
        if (SqfwFormSummaryFieldEnum.check_status_checked.getCode().equals(status)) {
            sqlStr.append(" and e.timeout_status ='0' and  e.check_status <> 3");
        }
        if (SqfwFormSummaryFieldEnum.check_status_init.getCode().equals(status)) {
            sqlStr.append(" and e.timeout_status ='1' and  e.check_status <> 3");
        }
        if (SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode().equals(status)) {
            sqlStr.append(" and e.check_status = 3");
        }
        if (StringUtils.isNotBlank(content)) {
            sqlStr.append(" and (e.place_name like '%").append(content).append("%' or e.address like '%").append(content).append("%') ");
        }

        sqlStr.append(" order by e.check_status asc, e.fill_date desc, e.id desc");
        if (null != pageNo) {
            if (null == pageSize) {
                pageSize = 10;
            }
            if (pageNo >= 1) {
                pageNo = (pageNo - 1) * pageSize;
            }
            if (0 != pageSize) {
                sqlStr.append(" LIMIT ").append(pageSize).append(" OFFSET ").append(pageNo);
            }
        }

        List<NutMap> nutMapList = sqfwFormsummaryService.listMap(Sqls.create(sqlStr.toString()));
        return JSONUtil.toList(JSONUtil.toJsonStr(nutMapList), SqfwShopBaseInfoDTO.class);
    }

    private String buildFormSummarySql(Sys_user sysUser) {
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append(" select * from (   ");
        sqlStr.append(" select *,row_number() over(partition by shops_base_info_id order by fill_date desc) as num from shequ.sqfw_form_summary_new sfsn where   ");
        sqlStr.append(" type='").append(SupportBusinessTypeEnum.PUBLIC_SECURITY.getName()).append("'");
        sqlStr.append(" and province ='").append(sysUser.getProvince()).append("'");
        sqlStr.append(" and city ='").append(sysUser.getCity()).append("'");
        sqlStr.append(" and district ='").append(sysUser.getDistrict()).append("'");
        if (!CommonConstants.DIRECTLY_UNDER.equals(sysUser.getCounty())) {
            sqlStr.append(" and county ='").append(sysUser.getCounty()).append("'");
        }
        //sqlStr.append(" and county ='").append(sysUser.getCounty()).append("'");
        if (!CommonConstants.DIRECTLY_UNDER.equals(sysUser.getCommunity())) {
            sqlStr.append(" and community ='").append(sysUser.getCommunity()).append("'");
        }
        sqlStr.append(" ) b where b.num=1   ");
        return sqlStr.toString();
    }

    @Override
    public Result<?> downPdfLedger(DownExcelLedgerReqVo reqVo) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();

        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.PUBLIC_SECURITY.getName());
        if (StringUtils.isNotBlank(reqVo.getFillStartDate())) {
            cnd.and(Sqfw_formSummary_new::getFillDate, ">=", String.format("%s 00:00:00", reqVo.getFillStartDate()));
            cnd.and(Sqfw_formSummary_new::getFillDate, "<=", String.format("%s 23:59:59", reqVo.getFillEndDate()));
            Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());
            //拼接五级 省
            cnd.and(Sqfw_formSummary_new::getProvince, "=", user.getProvince());
            //拼接五级 市
            cnd.and(Sqfw_formSummary_new::getCity, "=", user.getCity());
            //拼接五级 区
            cnd.and(Sqfw_formSummary_new::getDistrict, "=", user.getDistrict());
            //拼接五级 街道
            cnd.and(Sqfw_formSummary_new::getCounty, "=", user.getCounty());
            //拼接五级 社区
            cnd.and(Sqfw_formSummary_new::getCommunity, "=", user.getCommunity());
        } else {
            cnd.and(Sqfw_formSummary_new::getSqfwId, "in", reqVo.getSqfwIds());
        }
        if (StringUtils.isNotBlank(reqVo.getShopInfoId())){
            cnd.and(Sqfw_formSummary_new::getShopsBaseInfoId, "=", reqVo.getShopInfoId());
        }
        cnd.desc(Sqfw_formSummary_new::getFillDate);
        List<Sqfw_formSummary_new> sqfwFormSummaryNews = sqfwFormsummaryNewService.query(cnd);
        List<String> sqfwFlowIdList = sqfwFormSummaryNews.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
        Cnd cndFlow = Cnd.where(Sqfw_completeflow::getId, "in", sqfwFlowIdList);
        cndFlow.and(Sqfw_completeflow::getFileType, "like", "%" + SqfwFormSummaryConstants.public_security + "%")
                .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                .and(Sqfw_completeflow::getResourcePath, "!=", "error")
                .orderBy("create_date", "asc");
        List<Sqfw_completeflow> flwoList = sqfwCompleteflowService.query(cndFlow);
        if (!flwoList.isEmpty()) {
            List<String> pdfPathList = flwoList.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
            String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, DownLoadFileNameEnum.DYL_PUBLIC_SECURITY_STANDING_PDF.getName() + DateUtil.format(new Date(), "yyyyMMddHHmmss"));
            generateExcelUrlVO.setExcelUrl(url);
        }
        generateExcelUrlVOS.add(generateExcelUrlVO);
        return Result.data(generateExcelUrlVOS);
    }

    @Override
    public Result<?> getPublicSecurityFormSummaryPage(PlaceParamDTO dto) {
        if (StringUtils.isBlank(dto.getServiceType())) {
            throw new ServiceException("业务类型不能为空！");
        }
        SummaryQueryReqVo summaryQueryReqVo = new SummaryQueryReqVo();
        summaryQueryReqVo.setQueryCondititons(Lists.newArrayList());
        summaryQueryReqVo.setPageNo(dto.getPageNo());
        summaryQueryReqVo.setPageSize(dto.getPageSize());
        summaryQueryReqVo.setFillDate(dto.getFillDate());
        summaryQueryReqVo.setFillType(dto.getServiceType());
        summaryQueryReqVo.setSort(dto.getSort());
        SqlExpressionGroup sql = null;
        String placeType = dto.getPlaceType();
        String shopInfoId = dto.getShopInfoId();
        if (StringUtils.isNotBlank(placeType)) {
            sql = new SqlExpressionGroup();
            if (SupportBusinessTypeEnum.PUBLIC_SECURITY.getName().equals(dto.getServiceType())) {
                sql.and(Cnd.exp("param_data ->>'placeType'", "in", Arrays.asList(placeType.split(","))));
            } else if (SupportBusinessTypeEnum.SAFE_CHECK.getName().equals(dto.getServiceType())) {
                sql.and(Cnd.exp("param_data ->>'type'", "in", Arrays.asList(placeType.split(","))));
            } else if (sysUserService.getUserById(SecurityUtil.getUserId()).getUnitName().contains(StreetEnum.WEI_QING_MEN_STREET.getName()) &&
                    SqfwFormSummaryConstants.safety_check.equals(dto.getServiceType())) {
                sql.and(Cnd.exp("param_data ->>'attributesOfInspectionUnits'", "in", Arrays.asList(placeType.split(","))));
            }
        }
        if (StringUtils.isNotBlank(shopInfoId)) {
            if (ObjectUtils.isEmpty(sql)) {
                sql = new SqlExpressionGroup();
            }
            sql.and(Cnd.exp(" shops_base_info_id ", "=", shopInfoId));
        }
        summaryQueryReqVo.setSqlExpressionGroup(sql);
        return summarySafetyService.listSummaryByPage(summaryQueryReqVo);
    }

    @Override
    public Result<?> getReportMaterials(String startTime, String endTime, String serviceType, String shopInfoId, String fileMark, String placeType) {

        if (StringUtils.isBlank(serviceType)) {
            throw new ServiceException("业务类型不能为空！");
        }
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup expressionGroup = cnd.where();
        expressionGroup.and(Sqfw_formSummary_new::getCreateBy, "=", SecurityUtil.getUserId());
        expressionGroup.and("type", "in", Arrays.asList(serviceType.split(",")));
        if (StringUtils.isNotBlank(startTime)) {
            expressionGroup.and(Sqfw_formSummary_new::getFillDate, ">=", String.format("%s 00:00:00", startTime));
        }
        if (StringUtils.isNotBlank(endTime)) {
            expressionGroup.and(Sqfw_formSummary_new::getFillDate, "<=", String.format("%s 23:59:59", endTime));
        }
        if (StringUtils.isNotBlank(shopInfoId)) {
            expressionGroup.and(Sqfw_formSummary_new::getShopsBaseInfoId, "=", shopInfoId);
        }
        if (StringUtils.isNotBlank(placeType)) {
            cnd.and("param_data ->>'placeType'", "in", Arrays.asList(placeType.split(",")));
        }
        List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.query(cnd);
        boolean isHaveData = !formSummaryList.isEmpty();

        List<DownFileTypesResVo> downFileTypesResVoList = Lists.newArrayList();
        /*Set<String> fileIndex = Sets.newHashSet();

        fileIndex.add(PublicSecurityFileEnum.PUBLIC_SECURITY_STANDING_BOOK_GSHQ.getCode());
        fileIndex.add(PublicSecurityFileEnum.PUBLIC_SECURITY_STANDING_PDF_GSHQ.getCode());*/
        //List<String> ids = formSummaryList.stream().map(Sqfw_formSummary_new::getSqfwId).distinct().collect(Collectors.toList());

        for (PublicSecurityFileEnum psf : PublicSecurityFileEnum.values()) {
            if (psf.getFileMark().equals(fileMark)) {
                String suffix = "docx".equals(psf.getSuffix()) ? "pdf" : psf.getSuffix();
                DownFileTypesResVo downFileTypesResVo = new DownFileTypesResVo();
                downFileTypesResVo.setFileName(String.format("%s.%s", psf.getName(), suffix));
                downFileTypesResVo.setFileType("xlsx".equals(suffix) ? "excel" : suffix);
                downFileTypesResVo.setLabel(psf.getLabel());
                downFileTypesResVo.setFileCode(psf.getCode());
                downFileTypesResVo.setHiveData(isHaveData);
                //downFileTypesResVo.setIds(ids);
                if (StringUtils.isNotBlank(psf.getPreviewImage())) {
                    downFileTypesResVo.setPreviewImage(Arrays.asList(psf.getPreviewImage().split(",")));
                } else {
                    downFileTypesResVo.setPreviewImage(Lists.newArrayList());
                }
                downFileTypesResVoList.add(downFileTypesResVo);
            }
        }
        // 组装返回参数
        Pagination pagination = new Pagination();
        pagination.setList(downFileTypesResVoList);
        pagination.setTotalCount(formSummaryList.size());
        return Result.data(pagination);
    }

    @Override
    public GenerateExcelUrlVO downloadTemplateByIndex(String index) {
        PublicSecurityFileEnum publicSecurityFileEnum = PublicSecurityFileEnum.getPublicSecurityFileByCode(index);
        if (ObjectUtils.isEmpty(publicSecurityFileEnum)) {
            throw new ServiceException("模板不存在");
        }
        GenerateExcelUrlVO resultVO = new GenerateExcelUrlVO();
        String fileName = publicSecurityFileEnum.getName() + "." + publicSecurityFileEnum.getSuffix();
        String emptyTemplate = publicSecurityFileEnum.getEmptyTemplatePath();
        String filepath = CommonFormOfficeUtils.getTemplatePathByOS(emptyTemplate);
        if (publicSecurityFileEnum.getSuffix().contains("doc")) {
            ByteArrayOutputStream byteArrayOutputStream = CommonFormOfficeUtils.generateWordDocument(new HashMap<>(), emptyTemplate, null, System.currentTimeMillis());
            GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = CommonFormOfficeUtils.wordUpload(byteArrayOutputStream, publicSecurityFileEnum.getName(), null);
            resultVO.setCreateConditionFlag(true);
            resultVO.setExcelUrl(generateWordAndPdfUrlVO.getWordUrl());
        } else {
            ExcelFileCreateParamBO excelFileCreateParam = new ExcelFileCreateParamBO();
            excelFileCreateParam.setTemplatePath(filepath);
            excelFileCreateParam.setSheetParam(null);
            excelFileCreateParam.setDataList(Lists.newArrayList());
            excelFileCreateParam.setFileName(fileName);
            excelFileCreateParam.setListNotLastRow(null);
            resultVO.setCreateConditionFlag(true);
            resultVO.setExcelUrl(createExcelAndUpload(excelFileCreateParam));
        }
        return resultVO;
    }

}
